﻿// Copyright (c) 2014 Converter Systems LLC

using ConverterSystems.UaBrowser.ViewModels;
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace ConverterSystems.UaBrowser
{
    /// <summary>
    /// Interaction logic for UaBrowserControl.xaml
    /// </summary>
    public partial class UaBrowserControl : UserControl, IDisposable
    {
        private TreeViewItem _dragItem;
        private Point? _dragPoint;

        public UaBrowserControl()
        {
            InitializeComponent();
        }

        public void Dispose()
        {
            var vm = DataContext as UaBrowserViewModel;
            if (vm != null)
            {
                vm.Dispose();
            }
        }

        private static T FindAncestor<T>(DependencyObject dependencyObject) where T : class
        {
            var target = dependencyObject;
            do
            {
                if (target is Visual)
                    target = VisualTreeHelper.GetParent(target);
                else
                    target = LogicalTreeHelper.GetParent(target);
            } while (target != null && !(target is T));
            return target as T;
        }

        private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _dragPoint = new Point?(e.GetPosition(null));
            _dragItem = FindAncestor<TreeViewItem>((DependencyObject)e.OriginalSource);
        }

        private void OnPreviewMouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && _dragPoint.HasValue && _dragItem != null)
            {
                var vector = _dragPoint.Value - e.GetPosition(null);
                if (Math.Abs(vector.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(vector.Y) > SystemParameters.MinimumVerticalDragDistance)
                {
                    var rdvm = _dragItem.DataContext as ReferenceDescriptionViewModel;
                    if (rdvm != null)
                    {
                        var vm = this.DataContext as UaBrowserViewModel;
                        var text = vm.FormatProperty(rdvm);
                        if (!string.IsNullOrEmpty(text))
                        {
                            DataObject data = new DataObject(System.Windows.DataFormats.Text, text);
                            DragDrop.DoDragDrop(_dragItem, data, DragDropEffects.Copy);
                            _dragItem = null;
                            _dragPoint = null;
                        }
                    }
                }
            }
        }
    }
}